package io.renren.system.oss.tool;

import io.renren.common.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

/**
 * 下载文件工具类
 */
@Slf4j
public class DownloadFiles {
    /**
     * 网络文件下载到服务器本地
     *
     * @param href 文件所在网络地址
     * @param path 下载后的文件路径和名称
     * @throws IOException
     */
    public void downloadFile(String href, String path) {
        InputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            URL url = new URL(href);
            URLConnection conn = url.openConnection();
            inputStream = conn.getInputStream();
            fileOutputStream = new FileOutputStream(path);
            int bytesum = 0;
            int byteread;
            byte[] buffer = new byte[1024];
            while ((byteread = inputStream.read(buffer)) != -1) {
                bytesum += byteread;
                fileOutputStream.write(buffer, 0, byteread);
            }
            fileOutputStream.close();
            inputStream.close();
        } catch (IOException e) {
            log.info("网络文件下载到服务器本地->出现IO异常，异常信息:{}", e.getMessage());
        }
        log.info("网络文件下载到服务器本地执行结束!");
    }

    /**
     * 服务器文件下载到用户终端
     *
     * @param filePath
     * @param fileName
     * @param request
     * @param response
     */
    public void downloadFile(String filePath, String fileName, HttpServletRequest request, HttpServletResponse response) {
        String ua = request.getHeader("User-Agent");
        log.info("filePath1={}", filePath);
        if (StringUtils.isEmpty(fileName)) {
            fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
        }
        File file = new File(filePath);
        log.info("fileName={}", fileName);
        try {
            if (file.exists()) {
                if (ua.indexOf("MSIE") != -1 || ua.indexOf("Trident") != -1) {
                    //IE下的文件下载中文乱码
                    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                } else {
                    response.setHeader("Content-Disposition", String.format("attachment;filename*=utf-8'zh_cn'%s", URLEncoder.encode(fileName, "UTF-8")));
                }
                response.setContentType("application/force-download");
                OutputStream out = response.getOutputStream();
                out.write(FileUtils.readFileToByteArray(file));
                out.flush();
                out.close();
            }
        } catch (IOException e) {
            log.info("服务器文件下载到用户终端时，出现IO异常，异常信息:{}", e.getMessage());
        }
        log.info("服务器文件下载到用户终端执行结束!");
    }
}
